﻿using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Dapper.Contrib.Extensions;
using pinduoduo.Model;
using pinduoduo.Util;
using Sunny.UI;
using Tk.Soc.Share.Common.Helpers;

namespace pinduoduo.Page
{
    public partial class AddressPage : UIPage
    {
        private Main mainForm;

        public AddressPage(Main mainForm)
        {
            InitializeComponent();
            this.mainForm = mainForm;

            InitDataGridView();
        }


        private async void InitDataGridView()
        {
            AddressDataGridView.AddColumn("序号", "num").SetFixedMode(50);
            AddressDataGridView.AddColumn("姓名", "name").SetFixedMode(200);
            AddressDataGridView.AddColumn("电话", "mobile").SetFixedMode(200);
            AddressDataGridView.AddColumn("地址", "address");

            AddressDataGridView.ReadOnly = true;
            AddressDataGridView.AutoGenerateColumns = false;

            var addressList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<PddAddressDBModel>();

            DataGridViewPagination.DataSource = addressList;
            DataGridViewPagination.ActivePage = 1;

        }

        private void OrderDataGridView_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.Cells[0].Value = string.Format("{0}", (e.Row.Index + 1) + (this.DataGridViewPagination.ActivePage - 1) * DataGridViewPagination.PageSize);
        }

        private void DataGridViewPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            AddressDataGridView.DataSource = pagingSource;
        }

        private async void uiButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;
            dialog.Title = "请选择文件夹";
            dialog.Filter = "所有文件(*.txt)|*.txt";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string file = dialog.FileName;
                string text = File.ReadAllText(file);
                if (string.IsNullOrWhiteSpace(text))
                {
                    MessageBox.Show("数据为空");
                    return;
                }

                ShowWaitForm();

                string[] striparr = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                var addressList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<PddAddressDBModel>();
                int index = 1;
                foreach (var item in striparr)
                {
                    try
                    {
                        string[] sArray1 = item.Split(new char[4] { '-', '-', '-', '-' }, StringSplitOptions.RemoveEmptyEntries);
                        if (sArray1.Length != 3)
                        {
                            continue;
                        }
                        string name = sArray1[0];
                        string mobile = sArray1[1];
                        string address = sArray1[2];
                        PddAddressDBModel pddAddressDBMode = new PddAddressDBModel();
                        pddAddressDBMode.name = name;
                        pddAddressDBMode.mobile = mobile;
                        pddAddressDBMode.address = address;
                        var pddT = addressList.Where(x => { return x.name == name; }).FirstOrDefault();
                        if (pddT != null)
                        {
                            await DataBaseHelper.SqLiteDBCon.UpdateAsync(pddAddressDBMode);
                        }
                        else
                        {
                            await DataBaseHelper.SqLiteDBCon.InsertAsync(pddAddressDBMode);
                        }
                        SetWaitFormDescription("已经导入" + index);
                        index++;
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Logger.Error("导入地址失败", ex);
                    }

                }

                mainForm.mainPage.UpdateAddressList();
                HideWaitForm();
                addressList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<PddAddressDBModel>();

                DataGridViewPagination.DataSource = addressList;
                DataGridViewPagination.ActivePage = 1;
            }
        }

        private async void uiButton2_Click(object sender, EventArgs e)
        {
            if (ShowAskDialog("是否要清空数据"))
            {
                await DataBaseHelper.SqLiteDBCon.DeleteAllAsync<PddAddressDBModel>();

                var addressList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<PddAddressDBModel>();
                mainForm.mainPage.UpdateAddressList();
                DataGridViewPagination.DataSource = addressList;
                DataGridViewPagination.ActivePage = 1;
            }
        }

        private async void uiButton3_Click(object sender, EventArgs e)
        {
            if (!ShowAskDialog("此功能将清理不在拼多多地址库的地址"))
            {
                return;
            }
            var addressList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<PddAddressDBModel>();
            var areaModelList = DataBaseHelper.SqLiteDBCon.GetAll<AreaModel>();
            foreach (var pddAddressDBModel in addressList)
            {
                string[] addressArr = pddAddressDBModel.address.Split(' ');
                if (addressArr.Length != 4)
                {
                    await DataBaseHelper.SqLiteDBCon.DeleteAsync(pddAddressDBModel);
                    continue;
                }

                var sheng = areaModelList.Where(x =>
                {
                    return x.region_type == 1 && (x.region_name == addressArr[0]);
                }).FirstOrDefault();
                if (sheng == null)
                {
                    Console.WriteLine(pddAddressDBModel.address);
                    await DataBaseHelper.SqLiteDBCon.DeleteAsync(pddAddressDBModel);
                    continue;
                }

                var shi = areaModelList.Where(x =>
                {
                    return x.region_type == 2 && sheng.region_id == x.parent_id && (x.region_name == addressArr[1]);
                }).FirstOrDefault();

                if (shi == null)
                {
                    Console.WriteLine(pddAddressDBModel.address);
                    await DataBaseHelper.SqLiteDBCon.DeleteAsync(pddAddressDBModel);
                    continue;
                }

                var xian = areaModelList.Where(x =>
                {
                    return x.region_type == 3 && shi.region_id == x.parent_id && (x.region_name == addressArr[2]);
                }).FirstOrDefault();

                if (xian == null)
                {
                    Console.WriteLine(pddAddressDBModel.address);
                    await DataBaseHelper.SqLiteDBCon.DeleteAsync(pddAddressDBModel);
                    continue;
                }

            }
            addressList = await DataBaseHelper.SqLiteDBCon.GetAllAsync<PddAddressDBModel>();
            mainForm.mainPage.UpdateAddressList();
            DataGridViewPagination.DataSource = addressList;
            DataGridViewPagination.ActivePage = 1;
            mainForm.mainPage.UpdateAddressList();
        }
    }
}
